﻿using System;
using System.Collections;

namespace Borg
{
    public static class EnumeratorEx
    {
        public static IEnumerator CombineEnumerators(params IEnumerator[] enumerators)
        {
            return new MultiEnumerator(enumerators);
        }

        private class MultiEnumerator : IEnumerator
        {
            private int _currentEnumerator;
            private readonly IEnumerator[] _enumerators;

            public MultiEnumerator(params IEnumerator[] enumerators)
            {
                if (enumerators == null)
                    throw new ArgumentNullException();

                _enumerators = enumerators;
            }

            public bool MoveNext()
            {
                while (_currentEnumerator < _enumerators.Length)
                {
                    if (_enumerators[_currentEnumerator].MoveNext())
                        return true;

                    _currentEnumerator++;
                }

                return false;
            }

            public void Reset()
            {
                throw new NotSupportedException();
            }

            public object Current
            {
                get
                {
                    if (_currentEnumerator == _enumerators.Length)
                        throw new InvalidOperationException();

                    return _enumerators[_currentEnumerator].Current;
                }
            }
        }
    }
}

